package org.jeecg.modules.chunk.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.chunk.entity.UploadFileParam;
import org.jeecg.modules.chunk.enums.LubanProperties;
import org.jeecg.modules.chunk.enums.RequestType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: jeecg-boot-parent
 * @ClassName: org.jeecg.modules.chunk.controller.FileChunkService
 * @Version: 1.0
 */
@Service
@Slf4j
public class FileChunkService {

    @Autowired
    private LubanProperties lubanProperties;

    public String uploadFile(UploadFileParam requestParam) {
        String token = getToken();
        HttpResponse response = HttpRequest.post(lubanProperties.getFileChunkUrl()+RequestType.UPLOADFILE.getUrl())
                .header("access-token",token).body(JSONUtil.toJsonStr(requestParam)).execute();
        log.info("======>RequestType.UPLOADFILE：{}",JSONUtil.toJsonStr(response.body()));
        return JSONUtil.toJsonStr(response.body());
    }

    private String getToken() {
        Map<String,String> appParams = new HashMap<>();
        appParams.put("appId",lubanProperties.getAppId());
        appParams.put("appSecret",lubanProperties.getAppSecret());
        HttpResponse response = HttpRequest.post(lubanProperties.getFileChunkUrl()+RequestType.TOKENGET.getUrl()).body(JSONUtil.toJsonStr(appParams)).execute();
        log.info("=====>RequestType.TOKENGET:{}",JSONUtil.toJsonStr(response));
        if(response.isOk()){
            JSONObject jsonObject = JSONUtil.parseObj(response.body());
            String token = jsonObject.getStr("data");
            return token;
        }
        log.info("=====>获取token请求失败重新获取！");
        return  getToken();
    }
}